using UnityEngine;
using System.Collections;
using UnityEditor;
using System.IO;
using System.Text;
using XML;

public class SerializeTextTool : MonoBehaviour {

    [MenuItem("Scary/Serialize Texts")]
	static void SerializeText()
    {
        WWW www = new WWW("file://" + Application.dataPath + "/../../Documents/Texts.csv");

        while (!www.isDone)
        {
        }


        string all = www.text;
        string[] withoutEndLine = all.Split('\n');

        OutStream stream = new OutStream();
        stream.Prolog("utf-8")
            .Start("TextManager");

        int size = withoutEndLine.Length - 1;
        for (int i = 1; i < size; ++i)
        {
            string[] txts = withoutEndLine[i].Split(';');
            string name = txts[0];
            string fr = txts[2];
            string en = txts[1];
            string de = txts[3];
            de = de.Substring(0, de.Length - 1);

            stream.Start("text")
                .Attribute("name", name)
                .Attribute("french", fr)
                .Attribute("english", en)
                .Attribute("german", de)
                .End();
        }

        SaveInFile("./Assets/Resources/XML/text.xml", stream);   
    }


    //Save in File
    private static void SaveInFile(string path, OutStream stream)
    {
        using (FileStream fs = File.Create(path))
        {
            AddText(fs, stream.Serialize(true));
        }
    }


    //Add Text to file
    private static void AddText(FileStream fs, string value)
    {
        byte[] info = new UTF8Encoding(true).GetBytes(value);
        fs.Write(info, 0, info.Length);
    }

}
